import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-08-15
 * Time: 15:29
 */
//案例3:递归遍历目录,查找文件,按照内容查找
public class demo13 {
    private static void search(File f, String key) {
        StringBuilder stringBuilder = new StringBuilder();
        try (Reader reader = new FileReader(f)) {
            char[] chars = new char[1024];
            while (true) {
                int n = reader.read(chars);
                if (n == -1) {
                    break;
                }
                String s = new String(chars, 0, n);//0~n的字符拼成字符串
                stringBuilder.append(s);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        if (stringBuilder.indexOf(key) == -1) {
            //没找到
            return;
        }
        System.out.println("文件: " + f.getAbsolutePath());
    }

    private static void scan(File cur, String key) {
        if (!cur.isDirectory()) {
            return;//不是目录
        }
        File[] files = cur.listFiles();
        if (files.length == 0 || files == null) {
            return;
        }
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                //是文件
                search(files[i], key);
            } else {
                //是目录,递归
                scan(files[i], key);
            }
        }

    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入要搜索的路径");
        String rootPath = scanner.next();
        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()) {
            System.out.println("路径不存在");
            return;
        }
        System.out.println("输入关键字");
        String key = scanner.next();
        scan(rootFile, key);
    }
}
